import json
import logging

from base.connection import get_db_session
from decimal import Decimal

from common.definition import OrderType
from conf import promotion

logger = logging.getLogger("helper")


def get_order(order_id):
    """
    获取订单记录

    get_order(15554810983567980)

    :param order_id:
    :return:
    """

    class Order(object):
        pass

    session = get_db_session([
        {"db_table": "sdet_order", "model": Order}
    ])
    order = session.query(Order).filter_by(sdef_order_id=order_id).first()
    session.close()
    return order


def get_goods_text(order_id):
    """
    获取订单商品和数量的文字

    get_goos_text(15554810983567980)

    :param order_id
    :return:
    """
    order = get_order(order_id)

    goods_info = json.loads(order.sdef_order_goods)
    goods_text = ""
    for g in goods_info:
        goods_name = g["goods_name"]
        count = Decimal(g["count"])
        goods_text += f"{goods_name} x {count} \n"

    return goods_text


def get_printer(store_id):
    """
    获取门店云打印机
    :param store_id:
    :return:
    """

    class Printer(object):
        pass

    session = get_db_session([
        {"db_table": "sdet_store_printer", "model": Printer},
    ])

    filters = dict(
        ebf_store_id=store_id,
        ebf_printer_status=1
    )

    printer = session.query(Printer).filter_by(**filters).first()
    session.close()
    return printer


def get_print_content(pay, total_fee):
    cart_goods = json.loads(pay.sdef_order_goods)
    room_id = pay.sdef_order_room_id
    ship_type = pay.sdef_order_ship_type
    create_time = pay.sdef_order_create_time.strftime("%Y-%m-%d %H:%M:%S")
    order_id = pay.sdef_order_id
    table_name = "序号"
    if ship_type == 3:
        table_name = "美团"
    content = "<CB>莱支好酒</CB><BR>"
    content += "................................<BR>"
    if len(bytes(f'-- {table_name}:{room_id} --', encoding='utf8')) > 20:
        content += "<C><L>-- {}: {} --</L></C><BR>".format(table_name, room_id)
    else:
        content += "<CB>-- {}:{} --</CB><BR>" . format(table_name, room_id)
    content += "下单时间：{}<BR>".format(create_time)
    content += "订单编号：{}<BR>".format(order_id)
    content += "※※※※※※  商品  ※※※※※※<BR>"
    content += "名称　　     单价   数量    金额<BR>"
    content += "--------------------------------<BR>"
    for g in cart_goods:
        name = g["goods_name"].replace(" ", "")
        price = g["goods_price"]
        count = g["count"]
        fee = "%.2f" % Decimal(price * count)
        if len(name) > 7:
            content += "{}<BR>".format(name)
            content += "<RIGHT>     　   {}   ×{}   {}</RIGHT><BR>".format(price, count, fee)
        elif len(str(fee)) > 5:
            content += "<RIGHT>{}　{}  ×{}  {}</RIGHT><BR>" . format(name, price, count, fee)
        else:
            content += "<RIGHT>{}　 {}  ×{}   {}</RIGHT><BR>".format(name, price, count, fee)

    content += "<BR>"
    content += "备注： <BR>"
    content += "--------------------------------<BR>"
    content += "合计：{}元<BR><BR>".format(total_fee)
    content += "※※※※※※※※※※※※※※※※<BR>"
    content += "<CB>* 欢迎下次光临 *</CB><BR>"
    return content


def get_offline_user_online_orders():
    """
    获取线下用户线上订单汇总报告

    get_offline_user_online_orders()

    """

    class Agency(object):
        pass

    class User(object):
        pass

    class Order(object):
        pass

    session = get_db_session([
        {"db_table": "ebt_agency", "model": Agency},
        {"db_table": "sdet_order", "model": Order},
    ])

    summary = []
    agencies = session.query(Agency).filter_by(ebf_agency_type=3).all()
    for agency in agencies:
        agency_id = agency.ebf_agency_id
        agency_uid = agency.ebf_agency_uid

        filters = dict(
            sdef_order_agency_uid=agency_uid,
            sdef_order_store_id=0,
            sdef_order_pay_status=1,
        )

        orders = session.query(Order).filter_by(**filters).all()

        # filters = text('sdef_order_agency_uid = :agency_uid and sdef_order_store_id = 0 and sdef_order_pay_status = 1')
        # orders = session.query(Order).filter(filters).params(agency_uid=agency_uid).all()
        # orders = session.query(Order).filter(
        #   Order.sdef_order_agency_uid = agency_uid).filter.all()

        if orders:
            logger.info(f"agency_id={agency_id} total {len(orders)} orders")
            order_count = len(orders)
            summary.append({"agency_id": agency_id, "order_count": order_count})

    return summary


def get_delivery_fee(order_type, cart_goods_array):
    """
    获取订单运费

    >>> get_delivery_fee(
    ... OrderType.NORMAL,
    ... [
    ...      {
    ...        "id": "573631115863884",
    ...        "count": 1,
    ...        "goods_img": "http://a.cn/a.jpg",
    ...        "goods_name": "wine",
    ...        "goods_price": 49.0,
    ...        "balance_rate": 0.1,
    ...        "unit": 2
    ...      }
    ... ])
    Decimal('0')

    """

    if order_type in [OrderType.BAR, OrderType.PICKUP_IN_STORE, OrderType.MEMBER, OrderType.FREE_CARD, OrderType.MEAL_DEDUCTION]:
        # 小酒馆订单没有运费
        return Decimal(0)

    count = 0
    goods_id = ""
    for g in cart_goods_array:
        goods_id = str(g['id'])
        unit = int(g['unit'])
        if unit < 100:
            count += unit * g['count']
        if count >= 6:
            return Decimal(0)  # 满箱包邮
    if count < 6:
        freight = Decimal(15) * Decimal(count)  # 每支加运费15元
        if count == 2 and goods_id in [promotion.NEW_CUSTOMER_PROMO_GOODS_ID]:  
            # 新人礼包邮
            freight = Decimal(0)
            return freight
        return freight
    return Decimal(0)  # 满箱包邮
